package cn.wolfcode.crm5.interceptor;


import cn.wolfcode.crm5.annotation.RequiredPermission;
import cn.wolfcode.crm5.domain.User;
import cn.wolfcode.crm5.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    @Lazy//在用到的时候才加载
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User)request.getSession().getAttribute("USER_IN_SESSION");

        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod method = (HandlerMethod) handler;
        RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
        if (annotation == null){
            return true;
        }
        String expression = annotation.expression();

        List<String> expressions = permissionService.findPermissionByUserId(user.getId());

        if (expressions.contains(expression)){
            return true;
        }

        response.sendRedirect("/nopermission");
        //request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl").forward(request,response);
        return false;
    }
}
